<template>
    <div class="flow">
        <div class="flow-header">
            <span v-for="(item, index) in header" :key="index"
                :class="data.select == index ? 'select-header' : 'header-title'" @click="selectHeader(item, index)">{{
                    item }}</span>
        </div>
        <!-- 列表 -->
        <div class="iconCategory" v-if="data.select == 0">
            <!-- 系统 -->
            <div class="system">
                <div class="levelB" v-for="(item, index) in systemList" :key="index" @click="openUrl(item)">
                    <!-- <a style="color:#666" :href="item.url" :target="item.url.indexOf('http')!=-1?'_blank':''"> -->
                    <img class="icon" :src="item.imgSrc" />
                    <span class="text">{{ item.name }}</span>
                    <!-- </a> -->
                </div>
            </div>
        </div>
        <div class="iconCategory" v-if="data.select == 1">
            <!-- 流程 -->
            <div class="flow-li system">
                <div class="li-box" v-for="(item, index) in props.flowList" :key="index" @click="flowClick(item)">
                    <div class="pull-left">
                        <span class="label-primary">{{ index + 1 }}</span>
                        <span class="w2link">{{ item.formName }}</span>
                    </div>
                    <div class="pull-right">
                        <div class="badge">{{ item.badge }}+</div>
                    </div>
                </div>
            </div>
            <div class="inCommon">
                <div class="inCommon-list"></div>
                <div class="more">
                    <span class="icon" @click="flowMoresClick">{{ $t('webAuto.more') }}</span>
                </div>
            </div>
        </div>
        <!-- 发起打开流程 -->
        <w-dialog v-if="openItemDl" :ok-loading="submitLoading"
            :title="`${$t('webAuto.initiate')} - ${selectForm.formName}`" closeFree v-model="openItemDl"
            :okText="$t('webAuto.Submit')" :cancelText="$t('webAuto.cancel')" :onFlieText="$t('webAuto.SaveDraft')"
            @cancel="openItemDl = false" @ok="submitForm" @onFlie='submitForm2' :fullscreen="true"
            style="margin:0px !important;">
            <initiate-process ref="processForm" @render-ok="submitLoading = false" :code="selectForm.formId"
                v-if="openItemDl" @fail="submitLoading = false" @ok="openItemDl = false, submitLoading = false"
                style="width:98%" :draft="formDatas" />
        </w-dialog>

        <!-- 存稿弹框 -->
        <el-dialog v-if="openItemDl2" :close-on-click-modal="false" :ok-loading="submitLoading"
            :title="`${$t('homePage.pleaseDraft')} - ${selectForm.formName}`" closeFree width="40%"
            v-model="openItemDl2">
            <el-table :data="tableData" stripe style="width: 100%;margin:0 auto;" highlight-current-row
                @row-dblclick="rowDblClick"
                :header-cell-style="{ color: '#000', borderColor: ' #CCC', background: '#f9f9f9' }">
                <el-table-column type="index" width="50" label="#" />
                <el-table-column prop="name" :label="$t('webAuto.ManuscriptNumber')" />
                <el-table-column prop="address" :label="$t('webAuto.operate')" width="150">
                    <template #default="scope">
                        <el-button type="text" @click="handleClick(scope.row)" style="color:red">{{ $t('webAuto.delete')
                        }}</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="openForm">
                        {{ $t('webAuto.DoDraft') }}
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { onMounted, reactive } from "vue";
import InitiateProcess from '../../workspace/InitiateProcess.vue'
import { useRouter } from 'vue-router'
/**
     * Card 内容卡
     * @description
     * @property {String} header 标题
     * @property {String} selectHeader 默认选择那个标题
     * @property {Array} list 中间内容展示的数据
*/
const props = defineProps({
    header: {
        type: Array,
        default: ''
    },
    selectHeader: {
        type: Number,
        default: 0
    },
    systemList: {
        type: Array,
        default: []
    },
    flowList: {
        type: Array,
        default: []
    }
})
const data = reactive({
    select: null,
})
onMounted(() => {
    data.select = props.selectHeader; // 初始化时，选中默认的头部
})
const emit = defineEmits(['setSystem']);
// 触发向父组件传值
// 点击头部标题，向父组件传值
const selectHeader = (item, index) => {
    data.select = index
    emit('setSystem', item);
}

// 第一個card的點擊事件
const openUrl = async (item) => {
    let jobNo = JSON.parse(localStorage.getItem('loginUser'))?.id || ""
    if (item.url.indexOf('http') !== -1) {
        if (item.url.indexOf('system') !== -1) {
            try {
                window.open(item.url, '_blank');
            } catch (error) {
                console.error('Error sending request:', error);
            }
        } else {
            window.open(item.url, '_blank');
        }

    } else {
        emit('setSystem', item);
    }
}

// 路由跳转
const router = useRouter()
// 更多
const flowMoresClick = () => {
    const { href } = router.resolve({ path: '/workspace/forms' });
    window.open(href, '_blank');
}
</script>

<script>
import { getStaging, getFormDataStaging, deleteFormDataStaging } from '@/api/modelGroup'
import store from '../../../store/index'

export default {
    data() {
        return {
            loading: false,
            openItemDl: false,
            openItemDl2: false,
            tableData: [],//存稿list的key
            tableList: {},//存稿的list
            draft: false,//是否存稿
            selectForm: {},
            formDatas: {},
            formItem: {},
            actives: [],
        }
    },
    computed: {
        isMobile() {
            return window.screen.width < 450
        },
        loginUser() {
            return this.$store.state.loginUser
        },
        searchResult() {
            let result = []
            this.formList.list.forEach((group) => {
                group.items.forEach((item) => {
                    if (item.formName.indexOf(this.searchForm) > -1) {
                        result.push(item)
                    }
                })
            })
            return result
        },
    },
    methods: {
        refresh() {
            window.location.reload()
        },
        // 发起流程打开的画面
        enterItem(item) {
            console.log(item)
            if (!this.$isNotEmpty(item.processDefId)) {
                this.$message.warning('该流程还未发布😥')
                return
            }
            this.selectForm = item
            this.openItemDl = true
            this.recentlyUsed.removeByKey('formId', item.formId)
            this.recentlyUsed.unshift(item)
            if (this.recentlyUsed.length >= 20) {
                this.recentlyUsed.splice(1, this.recentlyUsed.length - 1)
            }
            localStorage.setItem(
                `recentlyUsed:${(this.loginUser || {}).id}`,
                JSON.stringify(this.recentlyUsed)
            )
            if (this.isMobile) {
                this.$router.push('/mbinitiate?code=' + item.formId)
            }
        },
        // 存稿弹框操作
        flowClick(item) {
            console.log(item)
            this.openItemDl2 = true
            this.selectForm = item
            this.tableData = []
            getFormDataStaging(item.formId).then(res => {
                console.log(res)
                if (res.status == 200) {
                    Object.keys(res.data).forEach(a => {
                        this.tableData.push({
                            name: a
                        })
                    })
                    this.tableList = res.data
                    if (!this.tableData.length) {
                        this.openItemDl2 = false
                        this.enterItem(this.selectForm)
                    }
                }
            })
            // .catch(err => {
            //     this.$err(err, '获取存稿数据失败')
            // })

        },
        // 提交流程
        submitForm() {
            this.$refs.processForm.validate((validForm, validProcess) => {
                console.log(this.$refs.processForm)
                if (!this.isMobile) {
                    if (validForm && validProcess) {
                        localStorage.removeItem('formItem');
                        store.commit('formItemClear')
                        this.$refs.processForm.submit()
                    } else {
                        this.$message.warning(this.$t('webAuto.refineOptions'))
                    }
                }
            })
        },
        //过滤前端undefined的值
        cleanUndefined(obj) {
            if (typeof obj === 'object' && obj !== null) {
                if (Array.isArray(obj)) {
                    return obj.map(item => this.cleanUndefined(item));
                } else {
                    const cleaned = {};
                    for (const key in obj) {
                        const value = obj[key];
                        cleaned[key] = value === undefined ? '' : this.cleanUndefined(value);
                    }
                    return cleaned;
                }
            } else {
                return obj === undefined ? '' : obj;
            }
        },
        // 保存存稿
        submitForm2() {
            this.$refs.processForm.validate((validForm, validProcess) => {
                // console.log('表单谢谢', this.$refs.processForm)
                //  存稿的相关逻辑
                if (!this.$refs.processForm.formData.stagingDate) {
                    this.$refs.processForm.formData.stagingDate = null
                }
                console.log('formId', this.selectForm.formId)
                getStaging({
                    formId: this.selectForm.formId,
                    param: this.cleanUndefined(this.$refs.processForm.formData)
                }).then(res => {
                    // console.log(res)
                    this.$message.warning(this.$t('webAuto.ProcessDraft') + res.data)
                })
            })
        },
        //不使用存稿的状态
        openForm() {
            this.openItemDl2 = false
            this.formDatas = {}
            this.enterItem(this.selectForm)
        },
        // 删除存稿
        handleClick(item) {
            deleteFormDataStaging({
                stagingDate: item.name,
                formId: this.selectForm.formId
            }).then(res => {
                this.$message.warning(res.data)
                let subscript = ''
                this.tableData.filter(function (value, index, arr) {
                    if (value.name == item.name) {
                        subscript = index
                    }
                });
                this.tableData.splice(subscript, 1)
            }).catch(err => {
                this.$message.warning(this.$t('webAuto.DeleteFailed') + err.data)
            })
        },
        // 使用存稿打开的方法
        rowDblClick(row) {
            console.log(row)
            this.draft = true
            this.formDatas = this.tableList[row.name]
            this.openItemDl = true
            this.openItemDl2 = false
        }
    },
}
</script>


<style scoped lang="less">
.flow {
    height: 100%;
    width: 100%;
    box-sizing: border-box;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    &-header {
        background-color: rgb(255, 255, 255);
        color: rgb(51, 51, 51);
        font-size: 17px;
        height: 45px;
        line-height: 45px;
        border-bottom: 1px solid rgb(221, 221, 221);
        padding: 0 15px;

        .header-title {
            padding: 6px 8px;
            color: inherit;
            font-weight: 400;
            border-bottom: none;
        }

        .select-header {
            cursor: pointer;
            padding: 6px 8px;
            color: rgb(234, 10, 42);
            font-weight: 600;
            border-bottom: 2px solid rgb(234, 10, 42);
        }
    }

    .iconCategory {
        flex: 1;
        overflow: hidden;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
    }
}

.system {
    margin: 20px 10px 10px 10px;
    box-sizing: border-box;
    width: 100%;
    display: flex;
    flex-wrap: wrap;


    .levelB {
        flex: 0 0 25%;
        padding: 0;
        // width: 100px;
        // min-width: 100px;
        height: 85px;
        margin-bottom: 15px;
        position: relative;
        text-align: center;

        .icon {
            display: block;
            width: 60px;
            height: 60px;
            margin: auto;
            border-radius: 12px;
            box-shadow: 0px 0px 3px #aaa;
            text-align: center;
            line-height: 60px;
        }

        .text {
            display: block;
            text-align: center;
            margin-top: 5px;
            margin-bottom: 15px;
            font-size: 14px;
            overflow: hidden;
            padding: 0 3px 0 3px;
        }
    }
}

.inCommon {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;

    &-list {
        flex: 1;
    }

    .more {
        background-color: rgb(255, 255, 255);
        color: rgb(0, 0, 0);
        height: 46px;
        line-height: 46px;
        padding: 0 15px;
        text-align: right;

        .icon {
            display: inline-block;
            text-rendering: auto;
            -webkit-font-smoothing: antialiased;
            position: relative;
            font-size: 16px;
            cursor: pointer;
            font-size: 16px;
            color: rgb(51, 51, 51);
        }

        .icon::before {
            content: '+';
            position: absolute;
            left: -20px;
            top: -4px;
            content: '+';
            font-size: 26px;
            font-weight: 600;
        }
    }

}

.flow-li {
    display: flex;
    flex-direction: row;
    justify-content: flex-start; //从那开始排列
    flex-wrap: wrap; // 换行
    align-self: start;
    align-items: baseline;
    padding: 0 15px 0 0 !important;
    box-sizing: border-box;
    margin: 10px !important;

    .li-box {
        display: flex;
        flex-direction: row;
        width: 50%;
        height: 30px;
        padding: 0 8px;
        border-bottom: solid 1px #e8e8e8;
        box-sizing: border-box;

        .pull-left {
            width: 80%;
            overflow: hidden;

            .label-primary {
                display: inline;
                padding: 2px 5px;
                font-size: 13px;
                font-weight: 700;
                line-height: 1;
                color: #fff;
                text-align: center;
                white-space: nowrap;
                vertical-align: baseline;
                border-radius: .25em;
                margin-bottom: 5px;
                background-color: #777;
            }


            .w2link {
                margin-left: 10px;
                cursor: pointer;
                color: #666;
                line-height: 30px;
                background: linear-gradient(to right, #79b989, #e34b4b) no-repeat right bottom;
                /*即下划线（背景图）在默认情况下宽度为0 */
                background-size: 0 2px;
                /* 设定过度时间 */
                transition: background-size 1300ms;
                font-size: 13px;
            }

            .w2link:hover {
                /* 悬停 显示鼠标显示为手的形状*/
                cursor: pointer;
                /* 悬停 下划线的横向滑动位置为左 */
                background-position-x: left;
                /* 设定下划线宽度为100%展示 */
                background-size: 100% 2px;
            }
        }

        .pull-right {
            flex: 1;
            text-align: right;

            .badge {
                display: inline-block;
                height: 12px;
                min-width: 10px;
                padding: 3px 7px;
                font-size: 14px;
                color: #fff;
                text-align: center;
                white-space: nowrap;
                vertical-align: middle;
                border-radius: 10px;
                line-height: 12px;
                cursor: default;
                margin-top: 5.5px;
                background-color: rgb(245, 32, 32);
                letter-spacing: 2px;
            }
        }



    }
}

.li-box:nth-child(1)>.pull-left>.label-primary {
    background-color: #337ab7;
}

.li-box:nth-child(2)>.pull-left>.label-primary {
    background-color: #5cb85c;
}

.li-box:nth-child(3)>.pull-left>.label-primary {
    background-color: #5bc0de;
}

.li-box:nth-child(4)>.pull-left>.label-primary {
    background-color: #f0ad4e;
}
</style>
